﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using TcpServer.Orm;

namespace TcpServer.DataProcessor
{
    public class BaseInfoBufferAndHelper
    {

        private static List<V_Threshold> _thresholds;

        /// <summary>
        /// 获取基本信息：监测点、采集设备、污染物因子、阈值等
        /// </summary>
        /// <param name="mn"></param>
        /// <returns></returns>
        public static V_Threshold GetBaseWholeInfoByMn(string mn)
        {
            ThrsholdsInit();
            return _thresholds?.FirstOrDefault(t => t.DevCode != null && t.DevCode.Equals(mn));
        }

        private static void ThrsholdsInit()
        {
            if (_thresholds == null ||Hjt212Parser.MyTimer.IsToTheTime("BaseInfoBufferAndHelper.ThrsholdsInit",5) )
            {
                using (var ctx = new DustEntities())
                {
                    _thresholds = ctx.V_Threshold.OrderByDescending(t => t.MonitorTime).ToList();
                }
            }
        }

        public static V_Threshold GetBaseWholeInfoByMn(string mn, string factorCode, DateSection section)
        {
            ThrsholdsInit();
            if (section == null)
            {
                return
                    _thresholds?.OrderByDescending(t=>t.MonitorTime).FirstOrDefault(
                        t => t.DevCode != null && t.DevCode.Equals(mn) && t.因子代码 != null && t.因子代码.Contains(factorCode));
            }

            return _thresholds?.OrderByDescending(t => t.MonitorTime).FirstOrDefault(
                     t => t.DevCode != null && t.DevCode.Equals(mn) && t.因子代码 != null && t.因子代码.Contains(factorCode) && t.报警限值时间类型ID == section.Id);

        }


        private static List<监测因子编码> _factors;
        public static 监测因子编码 GetFactorByCode(string code)
        {
            if (_factors == null)
            {
                using (var ctx = new DustEntities())
                {
                    _factors = ctx.监测因子编码.ToList();
                }
            }
            return _factors?.FirstOrDefault(t => t.因子代码 != null && t.因子代码.Equals(code));
        }

        private static List<报警限值类型> _thresholdType;

        public static 报警限值类型 GetThresholdType(string cn)
        {
            if (_thresholdType == null || Hjt212Parser.MyTimer.IsToTheTime("BaseInfoBufferAndHelper.GetThresholdType", 5))
            {
                using (var ctx = new DustEntities())
                {
                    _thresholdType = ctx.报警限值类型.ToList();
                }
            }
            return _thresholdType?.OrderByDescending(t=>t.ID).FirstOrDefault(t => t.类型代码 != null && t.类型代码.Contains(cn));
        }

        private static List<报警限值时间类型> _alarmThrsholdTimeTypes;
        private static List<DateSection> _dateSections;

        public static DateSection GetAlarmThrsholdTimeType(DateTime date)
        {
            if (_alarmThrsholdTimeTypes == null || _dateSections == null || Hjt212Parser.MyTimer.IsToTheTime("BaseInfoBufferAndHelper.GetAlarmThrsholdTimeType", 5))
            {
                using (var ctx = new DustEntities())
                {
                    _alarmThrsholdTimeTypes = ctx.报警限值时间类型.ToList();
                    _dateSections = new List<DateSection>();
                    foreach (var typeItem in _alarmThrsholdTimeTypes)
                    {
                        var matches = Regex.Matches(typeItem.时间类型名称, "[0-9]+:[0-9]{2}");

                        if (matches.Count == 2)
                        {
                            int count = 0;
                            DateSection dateSection = new DateSection
                            {
                                Id = typeItem.ID
                            };
                            foreach (Match match in matches)
                            {
                                if (match.Success && match.Value.Length >= 4)
                                {
                                    var temp = match.Value.Split(':');
                                    if (temp.Length != 2) continue;
                                    if (count++ % 2 == 0)
                                    {
                                        dateSection.BeginHour = int.Parse(temp[0]);
                                        dateSection.BeginMinute = int.Parse(temp[1]);
                                    }
                                    else
                                    {
                                        dateSection.EndHour = int.Parse(temp[0]);
                                        dateSection.EndMinute = int.Parse(temp[1]);
                                    }

                                }
                            }
                            _dateSections.Add(dateSection);
                        }
                    }

                }
            }
            foreach (var section in _dateSections)
            {
                if (section.EndHour > section.BeginHour)
                {
                    if (date.Hour >= section.BeginHour && date.Hour <= section.EndHour)
                    {
                        return section;
                    }
                }
                if (section.EndHour < section.BeginHour)
                {
                    if (!(date.Hour <= section.BeginHour && date.Hour >= section.EndHour))
                    {
                        return section;
                    }
                }

            }
            return null;

        }

        public class DateSection
        {
            public int Id { get; set; }
            public int BeginHour { get; set; }
            public int BeginMinute { get; set; }
            public int EndHour { get; set; }
            public int EndMinute { get; set; }
        }

        public static DateSection GetAlarmThrsholdTimeType(string dateTypeName)
        {
            DateSection dateSection = new DateSection { Id = -1 };
            var matches = Regex.Matches(dateTypeName, "[0-9]+:[0-9]{2}");

            if (matches.Count == 2)
            {
                int count = 0;

                foreach (Match match in matches)
                {
                    if (match.Success && match.Value.Length >= 4)
                    {
                        var temp = match.Value.Split(':');
                        if (temp.Length != 2) continue;
                        if (count++ % 2 == 0)
                        {
                            dateSection.BeginHour = int.Parse(temp[0]);
                            dateSection.BeginMinute = int.Parse(temp[1]);
                        }
                        else
                        {
                            dateSection.EndHour = int.Parse(temp[0]);
                            dateSection.EndMinute = int.Parse(temp[1]);
                        }

                    }
                }
            }
            return dateSection;
        }

    }
}
